import Vue from 'vue'
import Router from 'vue-router'
import loginRouter from './modules/loginRouter.js'
import homeRouter from './modules/homeRouter.js'
import publicRouter from './modules/publicRouter.js'
import {
  cachesStorage
} from '../core/utils/modules/cachesUtils'
import {
  setTitle
} from '../core/utils/modules/routerUtils'
//解决elementUI路由重复点击报错的问题，勿删！！！
const originalReplace = Router.prototype.replace;
Router.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err);
};

Vue.use(Router)
const router = new Router({
  mode: 'hash',
  routes: [...loginRouter, ...homeRouter, ...publicRouter]
});

const loginName = 'login'; // 登录name
const homeName = 'home'; // 首页name
// 路由拦截 封装
const isLoginAdmin = (name) => {
  let token = cachesStorage('token', 'get');
  let nameArr = ['login'].join(','); // 不需要登录的name
  if (!token && !nameArr.includes(name)) {
    // 未登录 且 需要登录的页面name，跳转登录页login
    return {
      name: loginName
    }
  } else if (token && nameArr.includes(name)) {
    // 已登录 且 在登录、注册相关页面，跳转首页home
    return {
      name: homeName
    }
  } else if (!name) {
    // 页面不存在
    return {
      name: '404'
    }
  } else {
    return ''
  }
};
// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.meta.bg) {
    document.querySelector('body').setAttribute('style', 'background:' + to.meta.bg)
  } else {
    document.querySelector('body').setAttribute('style', 'background:#fff')
  }
  // let name = isLoginAdmin(to.name);
  name ? next(name) : next()

});
router.afterEach(to => {
  setTitle(to, router.app); // 设置浏览器title
  window.scrollTo(0, 0)
});

export default router